define(["app",
    "jquery",
    "resources/OrgResource","resources/UserExResource"],
function (app) {
    var deps = ["$scope","OrgResource","$modalInstance","type","title","orgType","singleOrg","singleUser","companyCode","UserExResource"];
    function orgUserPickerConferenceController($scope, OrgResource,$modalInstance,type,title,orgType,singleOrg,singleUser,companyCode,UserExResource) {
       $scope.typeDic = {
           org:{
              name : "org",
              chiName:"组织",
              keyField:"orgId",
              nameField:"orgName",
              searchTip:"请输入关键字搜索"
           },
           user:{
              name : "user",
              chiName:"人员",
              keyField:"userId",
              nameField:"userName",
              searchTip:"请输入关键字搜索"
           },
           space:{
               name : "space",
               chiName:"人员",
               keyField:"userId",
               nameField:"userName",
               searchTip:"请输入关键字搜索"
            }
       };
       $scope.type = $scope.typeDic[type || "org"];
       $scope.title = title;
       $scope.orgType = orgType || '-1';
       $scope.nodeCount = 0;
       $scope.selectedNodes = {};
       $scope.selfOrgs = {};
       $scope.searchObj = {};
       $scope.isSelectAll = false;
       $scope.companyCode=companyCode
       $scope.checkboxes = { 'checked': false, 'unchecked': true, items: {} };
       $scope.singleOrg = singleOrg;  //是否唯一，比如最多只能选择1个组织
       $scope.singleUser = singleUser;  //是否唯一，最多只能选择1个用户
       initData($scope, OrgResource,$modalInstance,type,UserExResource);
       initAction($scope, OrgResource,$modalInstance,type,UserExResource);
       initClose($scope, $modalInstance);
       $scope.changeDeleteImage=function (flag){
			var image =document.getElementById("changeDeleteImage");
			if(flag){
				image.src="images/delete2.png";
			}else{
				image.src="images/delete1.png";
			}
	    };
		
    }
    
    function initData($scope, OrgResource,$modalInstance,type,UserExResource){

    	// 自定义时间
    	$scope.timeChoose=0;
    	
        $scope.toInit = function(){
            $scope.searchObj.searchState = false;
        };

        /**加载根组织**/
        /*$scope.loadRootOrg = function() {
            OrgResource.queryOrgPid("0").success(function(list){
                $.grep(list,function(org){
                    return $scope.orgType == -1 || org.orgType == $scope.orgType;
                });
//                handleData($scope,list);
                $scope.orgs = list;
            });
        };*/
        
        $scope.loadRootOrg = function() {
            OrgResource.queryOrgPidAndCode("0",$scope.companyCode).success(function(list){
                $.grep(list,function(org){
                    return $scope.orgType == -1 || org.orgType == $scope.orgType;
                });
//                handleData($scope,list);
                $scope.orgs = list;
            });
        };
        
        
        $scope.checkAll = function (users) {
        	
        	if (!$scope.isSelectAll) {
        		if(users && users.length>0){
                    for(var i = 0;i<users.length;i++){
                        var user = users[i];
                        if(!$scope.selectedNodes[user.userId]){
                            $scope.selectedNodes[user.userId] = user;
                            $scope.nodeCount ++;
                        }
                    }
                    $scope.isSelectAll = true;
                }
        		
        	}else{
        		
        		if(users && users.length>0){
                    for(var i = 0;i<users.length;i++){
                        var user = users[i];
                        if($scope.selectedNodes[user.userId]){
                            delete $scope.selectedNodes[user.userId];
                            if( $scope.nodeCount  > 0){
                                $scope.nodeCount -- ;
                            }
                        }
                    }
                    $scope.isSelectAll = false;
                }
        		
        	}
            
        }


        // 展开/收起组织节点
        $scope.toggleOpenTree = function(org) {
            // 隐藏或展开下级组织
            org.isSubsShow = !org.isSubsShow;
            if(!org.isSubsShow){
                return;
            }
            $scope.loadSubsAndUsers(org);
        };
        
        //加载子组织和成员
        $scope.loadSubsAndUsers = function(org){
            // 加载下级组织和成员,noneSubs默认false,假设有子组织或成员，这样才有按钮可供点击
            if(!org.noneSubs
                && (!org.subs || org.subs.length==0)
                && (!org.users || org.users.length==0)){

                //获取下级组织和成员
                OrgResource.queryOrgPid(org.orgId).success(function(list){
                    org.subs = list;
                    if($scope.type.name == "org"
                        && (!org.subs || org.subs.length==0)){
                        org.noneSubs = true;
                    }
                    if($scope.type.name == "user"){
                        UserExResource.getUsersByOrg(org.orgId).success(function(users){
                            org.users = users;
                            if((!org.subs || org.subs.length==0)
                                && (!org.users || org.users.length==0)){
                                org.noneSubs = true;
                            }
                        });
                    }
                });
            }
        };
        //获取数据
        $scope.loadRootOrg();
    }

    function initAction($scope, OrgResource,$modalInstance,type,UserExResource){

        //判断一个组织节点是否应该被选中
        $scope.isOrgSelect = function(org){
            if($scope.type.name == "user"){
               return org.checkboxSelect;
            }else{
               return $scope.selectedNodes[org.orgId];
            }
        };
        
        $scope.selfOrg = function(org){
        	// $scope.selectedNodes 检查是否已选中该id
        	if($scope.selectedNodes[org.orgId]){
        		OrgResource.queryOrgsByPid(org.orgId, 0).success(function(data){// 所有
                	angular.forEach(data, function(node){
                		if($scope.selectedNodes[node.orgId]){
                			if( $scope.nodeCount  > 0){
                                $scope.nodeCount -- ;
                            }
                            delete $scope.selectedNodes[node.orgId];
                		}
                	});
                }).success(function(){
                	OrgResource.queryOrgsByPid(org.orgId, 1).success(function(data){// 一层
                    	angular.forEach(data, function(node){
                    		$scope.selectedNodes[node.orgId] = node;
                    		$scope.nodeCount ++;
                    	});
                    });
                });
        	}
        	org.isSelfOrg = !org.isSelfOrg;
        	if($scope.selfOrgs[org.orgId]){
        		delete $scope.selfOrgs[org.orgId];
        	} else {
        		$scope.selfOrgs[org.orgId] = org;
        	}
        };
        
        $scope.isSelfOrg = function(org){
        	if(org.isSelfOrg){
        		return "images/local_level_select.png";
        	}else {
        		return "images/local_level_gary.png";
        	}
        };

        $scope.toggleNode = function(node){
        	if(!$scope.selectedNodes[node[$scope.type.keyField]]){
        		//如果最多只能选择1个节点，则每次新增时先清空
        		if($scope.singleOrg || $scope.singleUser){
        			$scope.selectedNodes = {};
        			$scope.nodeCount = 0;
        		}
        		$scope.selectedNodes[node[$scope.type.keyField]] = node;
        		$scope.nodeCount ++;
    		  	}else{
    		  		if( $scope.nodeCount  > 0){
    		  			$scope.nodeCount -- ;
    		  		}
    		  	delete $scope.selectedNodes[node[$scope.type.keyField]];
    		  }
        };
        
        // 选择一个用户/组织 单元
        $scope.toggleNodes = function(org) {
        	if ($scope.singleOrg) { //单选组织
            	if($scope.selectedNodes[org.orgId]){ //取消选中
            		if($scope.nodeCount > 0){
        				$scope.nodeCount -- ;
                    }
                    delete $scope.selectedNodes[org.orgId];
        		}else{ //选中
                    if ($scope.nodeCount > 0) { //添加不同的节点,则清空旧选项
            			$scope.selectedNodes = {};
                        $scope.nodeCount = 0;
            		}
                    //添加新选项
        			$scope.selectedNodes[org.orgId] = org;
                    $scope.nodeCount ++;
        		}
            	return;
            }
        	
            //如果最多只能选择1个节点，则每次新增时先清空
            if($scope.singleOrg || $scope.singleUser){
                $scope.selectedNodes = {};
                $scope.nodeCount = 0;
                
            }
            /**
    		if(!$scope.selectedNodes[org.orgId]){
    			$scope.selectedNodes[org.orgId] = org;
                $scope.nodeCount ++;
    		}else{
    			if( $scope.nodeCount  > 0){
                    $scope.nodeCount -- ;
                }
                delete $scope.selectedNodes[org.orgId];
    		}**/
    		var level = 0; 
    		if($scope.selfOrgs[org.orgId]){ // 已被选择了本层
    			level = 1;
    		}
            OrgResource.queryOrgsByPid(org.orgId, level).success(function(data){
            	angular.forEach(data, function(node){
            		if(!$scope.selectedNodes[node.orgId]){
                		$scope.selectedNodes[node.orgId] = node;
                        $scope.nodeCount ++;
                	} else {
                		if( $scope.nodeCount  > 0){
                            $scope.nodeCount -- ;
                        }
                        delete $scope.selectedNodes[node.orgId];
                	}
            	});
            });
        };

        //高亮显示
        $scope.highlight = function(node,flag) {
            var text = flag=="org"? node.orgName:node.userName;
            if(!text || !$scope.searchObj.searchState){
                return text;
            }
            return text.replace(new RegExp($scope.searchObj.searchKeyTemp, 'gi'), '<span class="text-match">$&</span>');
        };

        $scope.search = function(){
            $scope.noneResult = false;
            $scope.searchResultOrgs = [];
            $scope.searchResultUsers = [];
            $scope.searchPostResultUsers = [];
            $scope.searchObj.searchState = true;
            $scope.searchObj.searchKeyTemp = $.trim($scope.searchObj.searchKey);
            if(!$scope.searchObj.searchKeyTemp || $scope.searchObj.searchKeyTemp==""){
               //回到初始状态
                $scope.toInit();
                $scope.searchResultUsers = [];
                return;
            }
            OrgResource.searchAdderss($scope.searchObj.searchKeyTemp).success(function(data){
                
            	if($scope.searchObj.searchKeyTemp==null || $scope.searchObj.searchKeyTemp==''){
            		$scope.searchResultUsers = [];
            		$scope.loading =false;
            		return;
            	}
            	if(!data){
                    $scope.noneResult = true;
                    $scope.searchResultUsers = [];
                    return;
                }
                
                if($scope.type.name=="user"){
                    $scope.noneResult = (!data.userList || data.userList.length==0)
                        && (!data.orgList || data.orgList.length==0);
                }else if($scope.type.name=="org"){
                    $scope.noneResult = (!data.orgList) || (data.orgList.length==0);
                }
                
                if(data.postSearchList != null && data.postSearchList.length > 0){
                	  $scope.noneResult  =  false;
                  };
                
                $scope.searchPostResultUsers = data.postSearchList;
                
                $scope.searchResultOrgs = data.orgList;
                if($scope.searchResultOrgs && $scope.searchResultOrgs.length>0){
                    $.each($scope.searchResultOrgs,function(index,org){
                        org.tooltipShow = true;
                    });
                }
                if($scope.type.name=="user"){
                    $scope.searchResultUsers = data.userList;
                }
            });
        };

        //监控enter输入键触发搜索
        $scope.enterSearch = function($event){
            if ($event.keyCode === 13) {
                $scope.search();
            }
        };

        // 组织前面的复选框分两种情况：如果是新增组织，则代表当前组织是否选中，如果是新增成员，复选框相对于全选框，用于选择当前组织下的成员
        $scope.toggleOrgSelect = function(org){
            if($scope.singleUser){
                org.isSubsShow = !org.isSubsShow;
                return;
            }

            if($scope.type.name == "org"){
            	$scope.toggleNodes(org);
            }else if($scope.type.name == "user"){
                org.checkboxSelect = !org.checkboxSelect;
                if(org.isSelfOrg){
                	UserExResource.userListByOrg(org.orgId).success(function(data){
                		$scope.processUsers(org, data);	
                	});
                	return;
                }
                UserExResource.getUsersByOrgAndChild(org.orgId, "", 0, 0).success(function(data){
                	$scope.processUsers(org, data);
                });
            }
        };

        $scope.processUsers = function(org, data){
            var users = data.content;
            if(users && users.length>0){
                for(var i = 0;i<users.length;i++){
                    var user = users[i];
                    if(org.checkboxSelect){
                        if(!$scope.selectedNodes[user.userId]){
                            $scope.selectedNodes[user.userId] = user;
                            $scope.nodeCount ++;
                        }
                    }else{
                        if($scope.selectedNodes[user.userId]){
                            delete $scope.selectedNodes[user.userId];
                            if( $scope.nodeCount  > 0){
                                $scope.nodeCount -- ;
                            }
                        }
                    }
                }
            }
        };
        
        $scope.deleteNode = function(id){
            delete $scope.selectedNodes[id];
            if( $scope.nodeCount  > 0){
                $scope.nodeCount -- ;
            }
        };
        
        $scope.postAllSelected = false;
        
        $scope.selectedAllPostNodes = function(){
     	   var len = $scope.searchPostResultUsers.length;
     	   
     	   if(!$scope.postAllSelected){
     		   if($scope.searchPostResultUsers){        		
         	     for(var i=0;i<len;i++){
         	    	 var user = $scope.searchPostResultUsers[i];
         	    	 if(!$scope.selectedNodes[user.userId]){
         	    		$scope.selectedNodes[user.userId] = user;
            	    	 $scope.nodeCount ++;	 
         	    	 }
         	     }	   
         	   }  
     		   $scope.postAllSelected = true;
     	   }else{
     		   for(var i=0;i<len;i++){
       	    	 var user = $scope.searchPostResultUsers[i];
       	         $scope.deleteNode(user.userId);
       	     }	
     		   $scope.postAllSelected = false;
     	   }
     	   
        };
        
        $scope.showPostFlag = false;
        
        $scope.openPostTree = function(){
        	if(!$scope.showPostFlag){
        		$scope.showPostFlag = true;
        	}else{
        		$scope.showPostFlag = false;
        	}
        };
        
        $scope.departmentFlag=1;
        $scope.company=1;
        $scope.company_local=1;
        $scope.chooseType=0;
        $scope.changeImage =function(type){
        	var obj=document.getElementById("department1");
    		var obj1=document.getElementById("company1");
    		var obj2=document.getElementById("company_local1");
        	if(type==1){
        		if($scope.departmentFlag==1){
        			$scope.departmentFlag=2;
        			$scope.company=1;
        			$scope.company_local=1;
        			$scope.chooseType=1;
        			obj.src="images/department.png";
        		}else{
        			$scope.departmentFlag=1;
        			$scope.company=1;
        			$scope.company_local=1;
        			$scope.chooseType=0;
        			obj.src="images/department1.png";
        		}
        		obj1.src="images/company1.png";
        		obj2.src="images/company_local1.png";
        	}
        	if(type==2){
        		if($scope.company==1){
        			$scope.company=2;
        			$scope.departmentFlag=1;
        			$scope.company_local=1;
        			$scope.chooseType=2;
        			obj1.src="images/company.png";
        		}else{
        			$scope.company=1;
        			$scope.departmentFlag=1;
        			$scope.company_local=1;
        			$scope.chooseType=0;
        			obj1.src="images/company1.png";
        		}
        		obj.src="images/department1.png";
        		obj2.src="images/company_local1.png";
        	}
        	
        	if(type==3){
        		if($scope.company_local==1){
        			$scope.company_local=2;
        			$scope.departmentFlag=1;
        			$scope.company=1;
        			$scope.chooseType=3;
        			obj2.src="images/company_local.png";
        		}else{
        			$scope.company_local=1;
        			$scope.departmentFlag=1;
        			$scope.company=1;
        			$scope.chooseType=0;
        			obj2.src="images/company_local1.png";
        		}
        		obj.src="images/department1.png";
        		obj1.src="images/company1.png";
        	}
        };
        
        
        /*var fifty=1;
        var onehundred=1;
        var onehundredandfifty=1;
        $scope.chooseTime =function (type){
        	var obj1=document.getElementById("fifty");
    		var obj2=document.getElementById("onehundred");
    		var obj3=document.getElementById("onehundredandfifty");
    		
        	if(type==1){
        		if(fifty==1){
        			fifty=2;
        			$scope.timeChoose=50;
        			onehundred=1;
        			onehundredandfifty=1;
        			obj1.src="images/time.png";
        		}else{
        			$scope.timeChoose=0;
        			fifty=1;
        			onehundred=1;
        			onehundredandfifty=1;
        			obj1.src="images/time1.png";
        		}
        		obj2.src="images/time1.png";
        		obj3.src="images/time1.png";
        	}
        	if(type==2){
        		if(onehundred==1){
        			$scope.timeChoose=100;
        			fifty=1;
        			onehundred=2;
        			onehundredandfifty=1;
        			obj2.src="images/time.png";
        		}else{
        			$scope.timeChoose=0;
        			fifty=1;
        			onehundred=1;
        			onehundredandfifty=1;
        			obj2.src="images/time1.png";
        		}
        		obj1.src="images/time1.png";
        		obj3.src="images/time1.png";
        	}
        	
        	if(type==3){
        		if(onehundredandfifty==1){
        			$scope.timeChoose=150;
        			fifty=1;
        			onehundred=1;
        			onehundredandfifty=2;
        			obj3.src="images/time.png";
        		}else{
        			$scope.timeChoose=0;
        			fifty=1;
        			onehundred=1;
        			onehundredandfifty=1;
        			obj3.src="images/time1.png";
        		}
        		obj1.src="images/time1.png";
        		obj2.src="images/time1.png";
        	}
        };*/
        
    }

    /**
     * 关闭的方法
     */
    function initClose($scope, $modalInstance) {
        $scope.close = function () {
            $modalInstance.close();
        };
        
        $scope.selectOk = function(){
        	$scope.users={}; 
        	$scope.users.data=$scope.selectedNodes;
        	$scope.users.chooseType=$scope.chooseType;
        	$scope.users.timeChoose=$scope.timeChoose;
            $modalInstance.close($scope.users);
            // 发送广播刷新页面
            //$scope.$emit('confAuthoryAddBroadCast');
        };
    }

    orgUserPickerConferenceController.$inject = deps;
    return app.lazy.controller("OrgUserPickerConferenceController", orgUserPickerConferenceController);
});